
package gui.std;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;

import util.Constants;
import app.Server;

@SuppressWarnings("serial")
public class GServer extends JFrame {

	public GServer() {
		initialize();
	}
	
	private void initialize() {
		server = new Server();
		
		setSize(WIDTH, HEIGHT);
		setTitle("Server App");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		
		mb = new JMenuBar();
		fileMenu = new JMenu("File");
		exitItem = new JMenuItem("Exit");
		
		fileMenu.add(exitItem);
		mb.add(fileMenu);
		setJMenuBar(mb);
		
		exitItem.setMnemonic('E');
		exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, KeyEvent.ALT_MASK));
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}	
		});
		
		getContentPane().add(sp = new ServerPanel(server));
		setVisible(true);
	}
	
	private static final int WIDTH = 540;
	private static final int HEIGHT = 480;
	
	private Server server;
	
	private JMenuBar mb;
	private JMenu fileMenu;
	private JMenuItem exitItem;
	
	@SuppressWarnings("unused")
	private ServerPanel sp;
}


@SuppressWarnings("serial")
class ServerPanel extends JPanel {
	
	public ServerPanel(Server server) {
		this.server = server;
		initialize();
		update();
	}
	
	public void close() {
		server.close();
	}
	
	private void initialize() {
		setLayout(new BorderLayout());

		west = new JPanel();
		east = new JPanel(new BorderLayout());
		infoUser =  new JPanel(new BorderLayout());
		infoServer = new JPanel();
		uList = new GUserList();
		uList.setDisplay(infoUser);
		uList.update(server.getUserList());

		west.add(uList);
		
		hSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(west), east);
		vSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, infoUser, infoServer);
		
		hSplit.setDividerLocation(230);
		
		add(hSplit);
		east.add(vSplit);
	}
	
	private void update() {
		new Thread() {
			public void run() {
				while (true) {
					try {
						uList.update(server.getUserList());
						sleep(Constants.UPDATE_SERVER_TIME);
					}
					catch (InterruptedException e){e.printStackTrace();}
				}
			}
		}.start();
	}
	
	private Server server;
	
	private JPanel west;
	private JPanel east;
	private JPanel infoUser;
	private JPanel infoServer;
	private GUserList uList;
	private JSplitPane hSplit;
	private JSplitPane vSplit;
}